package com.shop.interceptors;

import com.shop.service.util.JwtUtil;
import com.shop.util.CookieUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String oldToken = CookieUtils.getCookieValueByName(request, "tokenCookie");
        if (StringUtils.isEmpty(oldToken)) {
            return true;
        }
        try {
            JwtUtil.parseToken(oldToken);
        } catch (ExpiredJwtException e) {
            String username = (String) redisTemplate.opsForValue().get(oldToken);
            if (StringUtils.isEmpty(username)) {
                return true;
            }
            String token = JwtUtil.createTokenSingleInfo(20, "username", username);
            redisTemplate.opsForValue().set(token, username, 40, TimeUnit.MINUTES);
            CookieUtils.addCookie(response, "tokenCookie", token, false);
        }
        return true;
    }
}
